var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const joi = require('joi')


// 创建服务器的实例对象
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
  next()
})

app.use((err, req, res, next) => {

})


// 一定要在路由之前，封装 res.cc函数
app.use((req, res, next) => {

  // status:的值默认为1，表示失败的情况
  // err的值可能是一个错误的对象，也可能是一个错误的描述字符串
  res.cc = function (err, status) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    })
  }
  next()
})

// 一定要在路由之前配置解析 Token 的中间件  

const expressJWT = require('express-jwt')
const config = require('./config')
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^((?!my).)*$/],}))

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var articleRouter = require('./routes/article');
var xadminRouter = require('./routes/xadmin');

app.use('/api', indexRouter);
app.use('/api/users', loginRouter);
app.use('/api/article', articleRouter);
app.use('/api/xadmin', xadminRouter);


//错误中间件
app.use((err, req, res, next) => {

  // 验证失败的错误
  if (err instanceof joi.ValidationError) return res.cc(err)

  //捕获身份认证失败的错误
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
  //未知错误
  res.cc(err)
})

app.listen(8080, () => {
  console.log('http://127.0.0.1:8080/api');
})
module.exports = app;
